<?php


namespace app\api\controller\finance;


use app\api\controller\Api;
use app\common\order\model\OrderProtocol;
use util\Format;

class Unpaid extends Api
{
    public function index()
    {
        // 酒店协议
        $post = $this->request->post();

        $where = [];
        // 审核状态
        if (!empty($post['check_status'])) $where[] = ['OrderProtocol.check_status', 'in', $post['check_status']];
        // 付款性质
        if (!empty($post['pay_type'])) $where[] = ['OrderProtocol.pay_type_id', 'in', $post['pay_type']];
        // total检索
        if (!empty($post['total'])) $where[] = ['total', '=', $post['total']];
        // 付款区间检索

        $hasWhere = [];
        $hasWhere[] = ['Order.refund_status', '=', 0];
        // $hasWhere[] = ['Order.order_type', '<>', 2];
        if (!empty($post['user_id'])) $hasWhere[] = ['Order.user_id', 'in', $post['user_id']];
        if (!empty($post['company_id'])) $hasWhere[] = ['Order.company_id', 'in', $post['company_id']];
        if (!empty($post['store_id'])) $hasWhere[] = ['Order.store_id', 'in', $post['store_id']];
        if (!empty($post['category_id'])) $hasWhere[] = ['Order.category_id', 'in', $post['category_id']];
        if (!empty($post['order_type'])) $hasWhere[] = ['Order.order_type', 'in', $post['order_type']];
        if (!empty($post['sign_date_range'])) {
            $signDateRange = Format::dateRange($post['sign_date_range']);
            $hasWhere[] = ['Order.sign_date', 'between', $signDateRange];
        }
        if (!empty($post['Order.event_date_range'])) {
            $eventDateRange = Format::dateRange($post['event_date_range']);
            $hasWhere[] = ['Order.event_date', 'between', $eventDateRange];
        }
        if (!empty($post['keyword'])) $hasWhere[] = ['Order.contact_no|Order.bridegroom|Order.bridegroom_mobile|Order.bride|Order.bride_mobile', 'like', "%{$post['keyword']}%"];

        if (empty($post['is_export'])) {
            list($cfg) = Format::pagination($post);
            $model = OrderProtocol::hasWhere('order', $hasWhere);
            $pg = $model->with('order')->where($where)->order('id desc')->paginate($cfg);
            $rows = $pg->getCollection();
            foreach ($rows as $row) {
                $row->append(['type', 'user', 'check_tag']);
                $row->order->append(['category', 'company', 'cooperation', 'user', 'store', 'order_type_text', 'check_tag']);
            }

            $result = [];
            $result['list'] = $rows;
            $result['pagination'] = Format::pgResult($pg);
            return success($result);
        } else {
            $fileName = '【应付单】' . date('YmdHis');
            $url = \app\common\third\Excel::exportExcel($expData, $header, $fileName);
            return success(['url' => $url], '导出成功');
        }
    }
}